# crawler/crawler_manager.py

import threading
import time
from typing import Callable, Dict, Any
from data.data_store import DataStore

# 可选：根据配置决定使用 mock 还是 real
from config.settings import USE_MOCK_CRAWLER

if USE_MOCK_CRAWLER:
    from spiders.crawler.mock_crawler import start_mock_crawling as _start_crawling
else:
    from spiders.crawler.real_crawler import start_real_crawling as _start_crawling


def start_mock_crawling(
    platform: str,
    ctype: str,
    params: Dict[str, Any],
    data_store: DataStore,
    update_callback: Callable,
    status_callback: Callable[[str, str], None],
    finish_callback: Callable
):
    """
    对外暴露的统一接口（名字保留为 start_mock_crawling 以兼容现有代码）
    实际内部根据配置调用 mock 或 real 爬虫
    """
    # 可在此处做通用预处理，例如：
    # - 记录日志
    # - 验证参数合法性
    # - 清空旧数据（可选）
    # data_store.clear_items(platform, ctype)

    status_callback(f"启动 {platform} - {ctype} 采集...", "blue")

    # 启动爬虫（在子线程中执行，避免阻塞 GUI）
    thread = threading.Thread(
        target=_run_crawler_in_thread,
        args=(platform, ctype, params, data_store, update_callback, status_callback, finish_callback),
        daemon=True
    )
    thread.start()


def _run_crawler_in_thread(
    platform, ctype, params, data_store, update_callback, status_callback, finish_callback
):
    """
    在子线程中安全运行爬虫，并通过回调与主线程通信
    """
    try:
        # 调用实际的爬虫函数（mock 或 real）
        _start_crawling(
            platform=platform,
            ctype=ctype,
            params=params,
            data_store=data_store,
            update_callback=update_callback,
            status_callback=status_callback,
            finish_callback=finish_callback
        )
    except Exception as e:
        # 错误必须通过回调回传到主线程更新 UI
        status_callback(f"采集出错: {str(e)}", "red")
        # 可选：记录日志
        import traceback
        traceback.print_exc()